package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"SlowAdmin/pkg/auth"
	"encoding/json"
)

// AuthController 授权控制器
type AuthController struct {
	controllers.BaseController
}

var model = models.AdminUser{}

// @title 登录
func (this *AuthController) Login() {
	data := models.AdminUser{}
	json.Unmarshal(this.Ctx.Input.RequestBody, &data)

	if data.Username == "" {
		this.Fail("请填写用户名", nil)
		return
	}

	if data.Password == "" {
		this.Fail("请输入密码", nil)
		return
	}

	user, pass := model.Login(data.Username, data.Password)

	if pass {
		token, _ := auth.GenToken(user)
		this.Success("登录成功", controllers.Result{
			"userInfo": map[string]interface{}{
				"name":   user.Name,
				"avatar": user.AvatarId,
			},
			"token": token,
			"role":  user.RoleTree(),
		})
	} else {
		this.Fail("账号或密码错误", nil)
	}
}

// @title 获取用户信息
func (c *AuthController) UserInfo() {
	token := c.Ctx.Request.Header["Authorization"][0]

	user, err := auth.GetUserByToken(token)

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("ok", user)
}
